//
//  XWXSqliteDataBase.m
//  XWXSqlite
//
//  Created by 许卫星 on 17/9/4.
//  Copyright © 2017年 wxxu. All rights reserved.
//

#import "XWXSqliteDataBase.h"
#import "XWXSqliteDataBaseTool.h"
#import "XWXSqliteConfiguration.h"

@implementation XWXSqliteDataBase

- (XWXSqliteDataBase *)initWithDBWithDBName:(NSString *)databaseName
{
    if (self = [super init]) {
        [self openDBWithDBName:databaseName];
    }
    return self;
}

//根据数据库名称打开数据库
- (BOOL)openDBWithDBName:(NSString *)databaseName
{
    NSString *dbName = [XWXSqliteDataBaseTool getDBNameWithDBName:databaseName];
    NSString *dbPatch = [kCachePatch stringByAppendingPathComponent:dbName];
    
    self.databaseName = dbName;
    self.databasePath = dbPatch;

    if (sqlite3_open(dbPatch.UTF8String, (sqlite3 **)&_database) != SQLITE_OK) {
        NSLog(@"数据库打开失败");
        return NO;
    }
    return YES;
}

- (void)beginTransaction
{
    sqlite3_exec(_database, "begin transaction", nil, nil, nil);
}

- (void)commitTransaction
{
    sqlite3_exec(_database, "commit transaction", nil, nil, nil);
}

- (void)rollBackTransaction
{
    sqlite3_exec(_database, "rollback transaction", nil, nil, nil);
}

- (BOOL)isOpen
{
    return self.database != nil;
}

//关闭数据库
- (void)closeDB
{
    sqlite3_close(self.database);
    self.database = nil;
    self.databasePath = nil;
    self.databaseName = nil;
}

- (void)setDatabase:(void *)database
{
    _database = database;
}

//设置数据库名称
- (void)setDatabaseName:(NSString *)databaseName
{
    _databaseName = databaseName;
}

//设置数据库路径
- (void)setDatabasePath:(NSString *)databasePath
{
    _databasePath = databasePath;
}


- (void)dealloc
{
    [self closeDB];
}
@end
